package com.cswnode.demo.controller;

import com.cswnode.demo.entity.ChatMsg;
import com.cswnode.demo.entity.User;
import com.cswnode.demo.service.ChatMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

/**
 * @author csw
 * @create 2021/3/27 17:44
 */
@Controller
public class WsController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private ChatMsgService chatMsgService;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMsg chatMsg){
        User loginUser = (User) authentication.getPrincipal();
        chatMsg.setFrom(loginUser.getUsername());
        chatMsg.setFormNickName(loginUser.getUserNameCn());
        chatMsg.setCreateTime(LocalDateTime.now());
        chatMsgService.insert(chatMsg);
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }

}
